// pages/room_details/room_details.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 总价
    price: null,
    roomInfo: null,
    hotelInfo: null,
    todayDate: '10月18日',
    tomorrowDate: '10月19日',
    tianShu: null,
    tagList: [],
    roomCount: 1, // 房间数量
    guestName: '', // 住客姓名
    phoneNum: '',
    guestInfoList: [
      {
        guestName: '', // 住客姓名
      }
    ],
    // 时间
    arriveTimeText: '18:00 房间将整晚保留', // 显示的时间文本，初始值可自定义
    showDatetimePickerPopup: false, // 控制时间选择器弹出层是否显示
    currentTime: '18:00', // 初始化为 HH:mm 格式的字符串
    nameReg: "/^[\u4e00-\u9fa5]{2,10}$/", // 正确：正则表达式（无引号）
    phoneReg: "/^1[3-9]\d{9}$/", // 正确
  },
  // 时间
  // 显示时间选择器弹出层
  showDatetimePicker() {
    this.setData({
      showDatetimePickerPopup: true
    });
  },
  // 确认选择时间
  onDatetimeConfirm(event) {
    const selectedTime = event.detail; 
    const timeText = selectedTime+'房间将整晚保留';
    this.setData({
      arriveTimeText: timeText,
      showDatetimePickerPopup: false,
      currentTime: selectedTime // 更新为时间戳格式
    });
  },
  // 关闭弹出层（取消选择时）
  onPopupClose() {
    this.setData({
      showDatetimePickerPopup: false
    });
  },
  // 房间数量变化回调
  onRoomCountChange(event) {
    this.setData({
      roomCount: event.detail,
      price: event.detail * this.data.roomInfo.price * 100
    });
  const totalPerson = this.data.roomCount;
  const guestInfoList = [];
  for (let i = 0; i < totalPerson; i++) {
    guestInfoList.push({
      name: '', 
      // 可扩展其他字段，比如身份证号等：idCard: ''
    });
  }
  this.setData({
    guestInfoList: guestInfoList
  });
  },
  // 住客姓名输入回调
  onGuestNameInputChange(event) {
    const index = event.currentTarget.dataset.index;
    const value = event.detail;
    const guestInfoList = this.data.guestInfoList;
    guestInfoList[index].name = value;
    this.setData({
      guestInfoList: guestInfoList
    });
  },
  // 校验住客姓名
validateGuestNames() {
  const guestInfoList = this.data.guestInfoList;
  const that = this;
  for (const [index, guest] of guestInfoList.entries()) {
    const name = String(guest.name).trim(); // 强制转为字符串
    console.log(name);
    if (!name) {
      wx.showToast({
        title: `请填写第${index + 1}位住客姓名`,
        icon: 'none',
        duration: 1500
      });
      return false; // 中断校验
    }
    const regex = new RegExp(that.data.nameReg);
    console.log(regex.test(name));
    if (regex.test(name)) {
      wx.showToast({
        title: `第${index + 1}位住客姓名格式错误（仅支持2-10位中文）`,
        icon: 'none',
        duration: 1500
      });
      return false;
    }
  }
  return true; // 所有姓名校验通过
},
  // 电话信息回调
  onPhoneInputChange(e){
    this.setData({
      phoneNum: e.detail
    })
  },
  // 校验手机号
validatePhoneNumber() {
  const phoneNum = this.data.phoneNum.trim();
  if (!phoneNum) {
    wx.showToast({
      title: '请填写联系手机号',
      icon: 'none',
      duration: 1500
    });
    return false;
  }
  const regex = new RegExp(this.data.phoneReg);
  console.log(regex.test(phoneNum));
  if (regex.test(phoneNum)) {
    wx.showToast({
      title: '手机号格式错误',
      icon: 'none',
      duration: 1500
    });
    return false;
  }
  return true;
},
  // 提交订单
onSubmit() {
  // 1. 校验住客姓名
  if (!this.validateGuestNames()) return;
  // 2. 校验手机号
  if (!this.validatePhoneNumber()) return;
  // console.log(app.globalData.hotelInfo.managerId);
  const that = this
  const lhkOrders = {
    customerId: app.globalData.userInfo.userId,
    roomTypeId: app.globalData.roomInfo.roomTypeId,
    hotelId: that.data.hotelInfo.hotelId,
    ruzhu: that.formatDate2(app.globalData.startDate),
    likai: that.formatDate3(app.globalData.endDate),
    guestInfoList: that.data.guestInfoList,
    roomCount: that.data.roomCount,
    managerId: app.globalData.hotelInfo.managerId,
    price: that.data.price,
    phone: that.data.phoneNum
  };
  console.log(lhkOrders);
  wx.showLoading({ title: '提交中...' });
  // 模拟异步请求（实际替换为接口调用）
  setTimeout(() => {
    // wx.hideLoading();
    console.log(lhkOrders);
    wx.request({
      method: 'POST',
      url: 'http://localhost:8080/system/hotel_reservation/addOrder',
      header: {
        'content-type': 'application/json',
        'Authorization': app.globalData.token
      },
      data: lhkOrders,
      success:(res)=>{
        console.log(res);
        if(res.data.code == 200){
          wx.switchTab({
            url: '/pages/order/order',
          })
        }
      }
    })
    wx.showToast({
      title: '订单提交成功',
      icon: 'none',
      duration: 1500
    });
    // 提交成功后可跳转页面或重置表单
  }, 1000);
},
chooseArriveTime() {
    // 这里简单模拟，实际可调用小程序选择时间 API 或跳转新页面
    wx.showToast({
      title: '选择到店时间逻辑待实现',
      icon: 'none'
    });
  },
  goBack(){
    wx.navigateBack()
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  },
  formatDate2(date) {
    date = new Date(date);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${this.data.currentTime}:00`;
  },
  formatDate3(date) {
    date = new Date(date);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} 09:00:00`;
  },
  viewAllNotice() {
    // 可在此实现跳转到查看全部订房须知页面的逻辑
    wx.navigateTo({
      url: '/pages/hotel_notice/hotel_notice',
    })
  },
  onShow() {
    this.setData({
      hotelInfo: app.globalData.hotelInfo,
      todayDate: this.formatDate(app.globalData.startDate),
      tomorrowDate: this.formatDate(app.globalData.endDate),
      tianShu: app.globalData.tianShu,
      roomInfo: app.globalData.roomInfo,
      tagList: [{ icon: 'good-job', text: '价格最低 赞！您已选择本店最划算的客房！', rgb: 'rgb(248, 92, 44)' },
      { icon: 'bell', text: '客房紧张 该客房仅剩'+app.globalData.roomInfo.freeRooms+'间最后在不下单就没了', rgb: 'rgb(55, 127, 127)'},
      { icon: 'checked', text: '极速退 放心订！预定成功后15分钟内可免费退款', rgb: 'rgb(52, 124, 175)' }],
      price: app.globalData.roomInfo.price * 100
    })
    console.log(this.data.roomInfo);
  },
  onHide() {

  },

  onUnload() {

  },

  onPullDownRefresh() {

  },

  onReachBottom() {

  },

  onShareAppMessage() {

  }
})